import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/widget/image_asset_widget.dart';

/// 交易密码弹窗，输入6位数字，输入完成自动关闭并回传内容
class TransactionPasswordDialog extends StatefulWidget {
  final Function(String password) onCompleted;
  final VoidCallback? onCancel;

  const TransactionPasswordDialog({
    Key? key,
    required this.onCompleted,
    this.onCancel,
  }) : super(key: key);

  static Future<void> show(
    BuildContext context, {
    required Function(String) onCompleted,
    VoidCallback? onCancel,
  }) {
    return showDialog(
      context: context,
      barrierDismissible: false,
      useSafeArea: false,
      builder:
          (_) => TransactionPasswordDialog(
            onCompleted: onCompleted,
            onCancel: onCancel,
          ),
    );
  }

  @override
  State<TransactionPasswordDialog> createState() =>
      _TransactionPasswordDialogState();
}

class _TransactionPasswordDialogState extends State<TransactionPasswordDialog> {
  List<String> inputList = [];
  final FocusNode _focusNode = FocusNode();
  final TextEditingController _controller = TextEditingController();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      FocusScope.of(context).requestFocus(_focusNode);
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    _focusNode.dispose();
    super.dispose();
  }

  void _onChanged(String value) {
    // 只保留数字，最多6位
    value = value.replaceAll(RegExp(r'[^0-9]'), '');
    if (value.length > 6) value = value.substring(0, 6);
    inputList = value.split('');
    setState(() {});
    if (inputList.length == 6) {
      Future.delayed(const Duration(milliseconds: 100), () {
        Navigator.of(context).pop();
        widget.onCompleted(inputList.join());
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => FocusScope.of(context).requestFocus(_focusNode),
      child: Material(
        color: Colors.black.withOpacity(0.4),
        child: Center(
          child: Container(
            width: 336.px,
            padding: EdgeInsets.fromLTRB(29.px, 24.px, 28.px, 39.px),
            decoration: BoxDecoration(
              color: AppColors.backgroundColorGrey2,
              borderRadius: BorderRadius.circular(12.px),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Padding(
                  padding: const EdgeInsets.fromLTRB(0, 0, 0, 0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      // const SizedBox(width: 24),
                      Expanded(
                        child: Container(
                          height: 30.px,
                          // color: AppColors.fontColorRed,
                          child: Stack(
                            children: [
                              Center(
                                child: Text(
                                  '请输入交易密码',
                                  style: TextStyle(
                                    fontSize: 18.px,
                                    fontWeight: FontWeight.bold,
                                    color: AppColors.fontColor,
                                  ),
                                ),
                              ),
                              Positioned(
                                right: 0,
                                child: GestureDetector(
                                  onTap: () {
                                    Navigator.of(context).pop();
                                    widget.onCancel?.call();
                                  },
                                  child: Container(
                                    padding: EdgeInsets.fromLTRB(
                                      10.px,
                                      0,
                                      10.px,
                                      10.px,
                                    ),
                                    // color: AppColors.backgroundColorLightGreen,
                                    child: ImageAssetWidget(
                                      imageUrl:
                                          'static/images/wallet/password_close.png',
                                      width: 22.px,
                                      height: 22.px,
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                // onPressed: () {

                //                       },
                SizedBox(height: 33.px),
                GestureDetector(
                  onTap: () => FocusScope.of(context).requestFocus(_focusNode),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: List.generate(6, (i) => _buildPwdBox(i)),
                  ),
                ),
                // 隐藏的输入框
                SizedBox(
                  height: 0,
                  width: 0,
                  child: TextField(
                    controller: _controller,
                    focusNode: _focusNode,
                    keyboardType: TextInputType.number,
                    inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                    maxLength: 6,
                    enableInteractiveSelection: false,
                    autofocus: true,
                    onChanged: (v) {
                      _onChanged(v);
                      // 保持controller内容和inputList同步
                      _controller.value = TextEditingValue(
                        text: inputList.join(),
                        selection: TextSelection.collapsed(
                          offset: inputList.length,
                        ),
                      );
                    },
                    decoration: const InputDecoration(
                      border: InputBorder.none,
                      counterText: '',
                    ),
                    style: const TextStyle(color: Colors.transparent),
                  ),
                ),
                const SizedBox(height: 8),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildPwdBox(int i) {
    bool hasInput = i < inputList.length;
    return Container(
      width: 39.px,
      height: 39.px,
      alignment: Alignment.center,
      decoration: BoxDecoration(
        // border: Border.all(color: AppColors.borderGreen, width: 1.px),
        borderRadius: BorderRadius.circular(6.px),
        color: Color.fromRGBO(59, 62, 69, 1),
      ),
      child:
          hasInput
              ? Container(
                width: 14,
                height: 14,
                decoration: const BoxDecoration(
                  color: Colors.white,
                  shape: BoxShape.circle,
                ),
              )
              : const SizedBox.shrink(),
    );
  }
}
